const express = require('express')
const router = express.Router()
const multer = require('multer')
const COS = require('cos-nodejs-sdk-v5')
const path = require('path')
const config = require('../config')

// 配置COS实例
const cos = new COS({
  SecretId: config.cos.secretId,
  SecretKey: config.cos.secretKey,
  // 添加请求超时配置
  Timeout: 60000,
  // 开启调试模式
  Debug: true
})

// 检查存储桶是否可用
async function checkBucket() {
  console.log('当前COS配置:', JSON.stringify({
    bucket: config.cos.bucket,
    region: config.cos.region,
    secretId: config.cos.secretId ? '已配置' : '未配置'
  }, null, 2));
  try {
    const result = await cos.headBucket({
      Bucket: config.cos.bucket,
      Region: config.cos.region
    })
    console.log('存储桶状态检查成功:', result)
    return true
  } catch (err) {
    console.error('存储桶状态检查失败:', err)
    return false
  }
}

// 初始化检查
checkBucket().catch(err => {
  console.error('存储桶初始化检查失败:', err)
})

// 配置multer
const upload = multer({
  limits: {
    fileSize: config.upload.maxFileSize,
  },
  fileFilter: (req, file, cb) => {
    // 只允许上传音频文件
    if (!file.mimetype.startsWith('audio/')) {
      return cb(new Error('只允许上传音频文件'))
    }
    cb(null, true)
  }
})

// 音频文件上传接口
router.post('/audio', upload.single('audio'), async (req, res, next) => {
  console.log('接收到音频上传请求:', {
    headers: req.headers,
    fileInfo: req.file ? {
      originalname: req.file.originalname,
      size: req.file.size,
      mimetype: req.file.mimetype
    } : null
  })

  try {
    if (!req.file) {
      throw new Error('请选择要上传的音频文件')
    }

    // 检查存储桶状态
    const bucketAvailable = await checkBucket()
    if (!bucketAvailable) {
      throw new Error('存储服务暂时不可用，请稍后重试')
    }

    // 生成在COS中的文件key
    const fileKey = `audio/${Date.now()}-${path.basename(req.file.originalname)}`
    console.log('准备上传文件:', {
      fileKey,
      size: req.file.size,
      mimetype: req.file.mimetype
    })

    // 上传文件到COS
    const startTime = Date.now()
    const result = await cos.putObject({
      Bucket: config.cos.bucket,
      Region: config.cos.region,
      Key: fileKey,
      Body: req.file.buffer,
      onProgress: function(progressData) {
        console.log('上传进度:', JSON.stringify(progressData))
      }
    })
    const uploadTime = Date.now() - startTime
    console.log('文件上传完成:', {
      fileKey,
      etag: result.ETag,
      uploadTime: `${uploadTime}ms`
    })

    // 生成文件访问链接
    const fileUrl = `${config.cos.baseUrl}/${fileKey}`

    res.json({
      code: 0,
      message: '上传成功',
      data: {
        url: fileUrl,
        originalName: req.file.originalname,
        size: req.file.size,
        mimetype: req.file.mimetype
      }
    })
  } catch (err) {
    next(err)
  }
})

module.exports = router